package copyengine.network.http
{
    import copyengine.log.CELog;
    import copyengine.utils.CEMemoryHolder;
    import copyengine.utils.GeneralUtils;

    import flash.events.Event;
    import flash.events.IOErrorEvent;
    import flash.net.URLLoader;
    import flash.net.URLRequest;
    import flash.net.URLRequestMethod;

    /**
     * 用于发送和接受简单的Http请求, 只是对URLLoader的简单封装
     */
    public class CESimpleHttpRequest
    {
        private var mURL:String;
        private var mURLLoader:URLLoader;
        private var mResultHandle:Function;

        public static function call(_url:String, _data:*, _resultHandle:Function, _method:String = URLRequestMethod.POST):CESimpleHttpRequest {
            return new CESimpleHttpRequest(_url, _data, _resultHandle, _method);
        }

        public function CESimpleHttpRequest(_url:String, _data:*, _resultHandle:Function, _method:String = URLRequestMethod.POST) {

            CEMemoryHolder.instance.holdItem(this);
            mResultHandle = _resultHandle;

            var urlRequest:URLRequest = new URLRequest(_url);
            urlRequest.data = _data;
            urlRequest.method = _method;

            mURLLoader = new URLLoader();
            addListener();

            mURLLoader.load(urlRequest)
        }

        private function addListener():void {
            GeneralUtils.addTargetEventListener(mURLLoader, Event.COMPLETE, onLoaded);
            GeneralUtils.addTargetEventListener(mURLLoader, IOErrorEvent.IO_ERROR, onLoadInError);
        }

        private function removeListener():void {
            GeneralUtils.removeTargetEventListener(mURLLoader, Event.COMPLETE, onLoaded);
            GeneralUtils.removeTargetEventListener(mURLLoader, IOErrorEvent.IO_ERROR, onLoadInError);
        }

        private function onLoaded(e:Event):void {
            mResultHandle(mURLLoader.data);
            removeListener();
            mURLLoader = null;
            CEMemoryHolder.instance.releaseItem(this);
        }

        private function onLoadInError(e:IOErrorEvent):void {
            removeListener();
            CEMemoryHolder.instance.releaseItem(this);
            CELog.err(e.toString());
            CELog.err("CESimpleHttpRequest-> http request in error, url: " + mURL);
        }


    }
}
